package com.grablist.feihu.grablist.ui.actviity.user;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.grablist.feihu.grablist.R;
import com.grablist.feihu.grablist.base.BaseActivity;
import com.grablist.feihu.grablist.base.BaseBiz;
import com.grablist.feihu.grablist.bean.RechargeSettingInfo;
import com.grablist.feihu.grablist.comm.Constants;
import com.grablist.feihu.grablist.comm.MyApplication;
import com.grablist.feihu.grablist.event.NetErrorEvent;
import com.grablist.feihu.grablist.event.RechargeEvent;
import com.grablist.feihu.grablist.pay.AliPayManager;
import com.grablist.feihu.grablist.pay.IPayManager;
import com.grablist.feihu.grablist.pay.PayStates;
import com.grablist.feihu.grablist.pay.WXPayManger;
import com.grablist.feihu.grablist.pay.WxBean;
import com.grablist.feihu.grablist.ui.actviity.user.biz.RechargeBiz;
import com.grablist.feihu.grablist.ui.actviity.user.component.DaggerRechargeComponent;
import com.grablist.feihu.grablist.ui.actviity.user.contract.RechargeContract;
import com.grablist.feihu.grablist.ui.actviity.user.module.RechargeModule;
import com.grablist.feihu.grablist.ui.actviity.user.presenter.RechargePresenter;
import com.grablist.feihu.grablist.ui.adapter.RechargeAdapter;
import com.grablist.feihu.grablist.util.LogUtils;
import com.jakewharton.rxbinding.view.RxView;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.Bind;
import rx.functions.Action1;

/**
 * Created by admin on 2017/12/2.
 */

public class RecharegAct extends BaseActivity implements RechargeContract.View {


    @Inject
    RechargePresenter presenter;
    @Inject
    RechargeBiz biz;
    @Bind(R.id.needsx)
    TextView needsx;


    @Bind(R.id.rechagre_submit)
    TextView rechagreSubmit;
    String payType = "wxpay";//1 支付宝 0 微信
    @Bind(R.id.super_recycler_view)
    SuperRecyclerView superRecyclerView;
    private View footerVier;
    ImageView rechagreCheckWei;
    LinearLayout rechagreLayoutWei;
    ImageView rechagreCheckAli;
    LinearLayout rechagreLayoutAli;
    RechargeAdapter adapter;
    List<RechargeSettingInfo> mlist = new ArrayList<>();

    private AliPayManager aliPayManager;

    private IWXAPI api;



    @Override
    protected void setRoot() {
        setTitleBar("#FFFFFFFF");
        setContentView(R.layout.activity_recharge);

    }

    @Override
    protected void setup() {
        setStateText();
        DaggerRechargeComponent.builder().rechargeModule(new RechargeModule(this)).build().inject(this);
        setToolBar("账户充值", "");
        needsx.setText("我要退款");
        needsx.setVisibility(View.GONE);
        presenter.setBiz(biz);
    }


    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        aliPayManager = new AliPayManager(this);
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, true);
        api.registerApp(Constants.APP_ID);
        biz=new RechargeBiz();
        GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        superRecyclerView.setLayoutManager(layoutManager);
        superRecyclerView.setRefreshEnabled(false);// 可以定制是否开启下拉刷新
        superRecyclerView.setLoadMoreEnabled(false);// 可以定制是否开启加载更多
        footerVier = getLayoutInflater().inflate(R.layout.footer_recharge,
                (ViewGroup) superRecyclerView.getParent(), false);
        rechagreLayoutWei = (LinearLayout) footerVier.findViewById(R.id.rechagre_layout_wei);
        rechagreCheckWei = (ImageView) footerVier.findViewById(R.id.rechagre_check_wei);
        rechagreCheckAli = (ImageView) footerVier.findViewById(R.id.rechagre_check_ali);
        rechagreLayoutAli = (LinearLayout) footerVier.findViewById(R.id.rechagre_layout_ali);
        adapter = new RechargeAdapter(this, mlist);
        superRecyclerView.setAdapter(adapter);
        adapter.addFooterView(footerVier);
        RxView.clicks(needsx)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        presenter.toDrawBack();
                    }
                });

        RxView.clicks(rechagreLayoutWei)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        presenter.selectRecharge(1);
                    }
                });
        RxView.clicks(rechagreLayoutAli)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        presenter.selectRecharge(0);
                    }
                });

        RxView.clicks(rechagreSubmit)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        loading(true);
                        String id = "";
                        for (RechargeSettingInfo rechargeSettingInfo : adapter.getData()) {
                            if (rechargeSettingInfo.isSelected()) {
                                id = rechargeSettingInfo.getId();
                            }

                        }
                        LogUtils.d(id);
                        if (payType.equals("alipay")) {
                            aliPayManager.recharge(id, PayStates.PAY_ALI, new IPayManager.PayCallback() {
                                @Override
                                public void onSuccess() {
                                    showMsg("支付成功");
                                    loading(false);
                                    EventBus.getDefault().post(new RechargeEvent());
                                }

                                @Override
                                public void onFail() {
                                    showMsg("支付失败");
                                    loading(false);
                                }
                            });
                        } else {
                            biz.wexiConfirm(MyApplication.userInfo.getUserCode(), id, PayStates.PAY_WEIXIN, new BaseBiz.Callback<WxBean>() {
                                @Override
                                public void onSuccess(WxBean wxBean) {
                                    PayReq req = new PayReq();
                                    req.appId = wxBean.getAppid();
                                    req.partnerId = wxBean.getPartnerid();
                                    req.prepayId = wxBean.getPrepayid();
                                    req.packageValue = "Sign=WXPay";
                                    req.nonceStr = wxBean.getNoncestr();
                                    req.timeStamp = wxBean.getTimestamp();
                                    req.sign = wxBean.getSign();
                                    req.extData = "app data";
                                    api.sendReq(req);
                                    loading(false);
                                    EventBus.getDefault().post(new RechargeEvent());

                                }

                                @Override
                                public void onFailure(WxBean o) {
                                    LogUtils.d("2err:" + o);
                                    loading(false);
                                }
                            });
                        }
                    }
                });
        presenter.getSetting();

    }


    @Override
    public void onNetErrorEvent(NetErrorEvent event) {
        super.onNetErrorEvent(event);
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }

    /***
     * Stop location service
     */
    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        biz.onDestory();

    }


    @Override
    public void updateUI(List<RechargeSettingInfo> list) {
        mlist = list;
        adapter.setDatas(list);
        adapter.notifyDataSetChanged();

    }

    @Override
    public void updateRecgarge(int type) {
        if (type == 1) {
            rechagreCheckWei.setImageResource(R.mipmap.pay_check_true);
            rechagreCheckAli.setImageResource(R.mipmap.pay_check_false);
            payType = "wxpay";
        } else if (type == 0) {
            rechagreCheckWei.setImageResource(R.mipmap.pay_check_false);
            rechagreCheckAli.setImageResource(R.mipmap.pay_check_true);
            payType = "alipay";
        }
    }


}

